#!/bin/bash
# Author: fanyongfeng
# 安装keepalived
# 操作系统：centos7/银河麒麟v10-sp2

set -e

# 使用root用户执行
[[ $(id -u) -ne 0 ]] && echo "请使用root用户执行此脚本" && exit 1

usage(){
    echo "Usage:"
    echo "sh $0 --vip=VIP地址 --role=master或backup --peer_ip=另一台keepalived所在服务器的ip地址"
    exit 1
}

#处理参数，规范化参数
ARGS=$(getopt -o h --long vip:,peer_ip:,role:,help -n "$0" -- "$@")
if [[ $? != 0 || $# -eq 0 ]]
then
        usage
fi

#重新排列参数顺序
eval set -- "${ARGS}"
#通过shift和while循环处理参数
while true
do
    case $1 in
        --vip)
            VIP=$2
            shift 2
            ;;
        --role)
            ROLE=`echo $2 | tr a-z A-Z`
            shift 2
            ;;
        --peer_ip)
            PEER_IP=$2
            shift 2
            ;;
        -h|-help)
            usage
            exit 1            
            ;;
         --)
            shift
            break
            ;;
         *)
            echo "Internal error!"
            exit 1
            ;;
    esac
done

 
yum install keepalived -y
 
HOST_IP=$(ip a | grep global | head -1 | awk -F'/' '{print $1}' | awk '{print $2}')
INTERFACE_NAME=$(ip a | grep "${HOST_IP}" | awk '{print $NF}')
VIRTUAL_ROUTER_ID=$(echo "${VIP}" | awk -F'.' '{print $NF}')
PASSWORD='1111'

# 设置Keepalived主备优先级
PRIORITY=100
[[ ${ROLE} == "BACKUP" ]] && PRIORITY=90

\cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
cat > /etc/keepalived/keepalived.conf <<EOF
global_defs {
   script_user root
   enable_script_security
}
 
vrrp_script check_script {
   script "/etc/keepalived/check_script.sh"
   interval 2
   weight -20
}
 
vrrp_instance VI_1 {
    state ${ROLE}   
    nopreempt       # 非抢占模式,BACKUP模式下生效
    priority ${PRIORITY}    # 节点的优先级，可选值为 [1-255]
    interface ${INTERFACE_NAME}  # vip绑定的网口名
    virtual_router_id ${VIRTUAL_ROUTER_ID} # 设置VRID标记，取值在0-255之间。同一集群内virtual_router_id保持一致。
    # 使用单播模式
    unicast_src_ip  ${HOST_IP} # 本机内网ip
    unicast_peer {
        ${PEER_IP}    # 指向其他Keepalived主机IP地址
    }
    advert_int 1 # vrrp通告的时间间隔，默认1s
    authentication {
        auth_type PASS         # 认证类型
        auth_pass ${PASSWORD}  # 共享密钥，即相互认证密码
    }
    virtual_ipaddress {
        ${VIP}   # VIP
    }
    track_script {
        check_script
    }
}
EOF
 
touch /etc/keepalived/check_script.sh
chmod 755 /etc/keepalived/check_script.sh
 
 
# 如需检查nginx，打开以下注释
# cat > /etc/keepalived/check_script.sh <<EOF
# #!/bin/bash
# A=\$(ps -C nginx --no-header |wc -l)
# if [ \$A -eq 0 ];then
#         `ps -ef|grep nginx | grep -v grep |grep 'nginx: master process' | awk '{print $NF}'`
#         sleep 2
#         [ \$(ps -C nginx --no-header |wc -l) -eq 0 ] || exit 1
# fi
# EOF
 
# 如需检查mysql，打开以下注释
# cat > /etc/keepalived/check_script.sh <<EOF
# #!/bin/bash
# service mysqld status
# [[ \$? -eq 0 ]] || exit 1
# EOF

# 启动Keepalived
systemctl daemon-reload
systemctl enable keepalived
systemctl start keepalived
systemctl status keepalived